package com.ry.shiro.realm;

import com.ry.dao.UserDao;
import com.ry.vo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.*;

public class CustomRealm extends AuthorizingRealm {

    @Resource
    private UserDao userDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        //从数据库 获取角色
        Set<String> roles = getRolesByUserName(username);
        //从数据库 获取资源
        Set<String> permissions = getPermissionsByUserName(username);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

    private Set<String> getRolesByUserName(String username) {
        System.out.println("从数据库中获取权限数据");
        List<String> list = userDao.queryRolesByUserName(username);
        Set<String> set = new HashSet<>(list);
        return set;
    }

    private Set<String> getPermissionsByUserName(String username) {
        Set<String> set = new HashSet<>();
        set.add("permit:delete");
        return set;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从 subject中获取用户名
        String userName = (String)authenticationToken.getPrincipal();
        //通过用户名到数据库获取凭证
        String password = getPasswordByUserName(userName);
        if(password == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName,password,"customRealm");

        //盐也应该保存在数据库中
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("admin"));

        return authenticationInfo;
    }

    private String getPasswordByUserName(String userName)
    {
        User user = userDao.getUserByUserName(userName);
        if (user != null){
            return user.getPassword();
        }else{
            return null;
        }

    }


    /**
     * 数据库密码 加Realm  MD5认证
     * @param args
     */
    public static void main(String[] args) {
        Md5Hash md5Hash =new Md5Hash("123456","admin");
        System.out.println(md5Hash.toString());
    }
}
